<?php

namespace app\beautiful\model;

use app\common\model\CommonModel;
use think\facade\Db;


class LevelModel extends CommonModel{

    protected  $name = 'beautiful_level';

    protected  $pk   = 'level_id';

    public function getById($where,$field='*')
    {
        $list = $this->where($where)->field($field)->find();
        if($list) $list = $list->toArray();

        return $list;
    }
    public static function list($where,$order,$page=0,$limit=0,$field='*'){
        $query = self::where($where)->field($field);
        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->select()->toArray();

        return compact('count','list');
    }
    public function getList($where,$order,$page=0,$limit=0,$field='*'){
        $query = Db::name('beautiful_level')->alias('l')
            ->leftjoin('beautiful_level_benefits lb','lb.level_id=l.level_id and lb.is_delete=0')
            ->leftjoin('beautiful_coupon c','c.coupon_id=lb.coupon_id and c.is_delete=0 and c.status=1')
            ->where(['l.is_delete'=>0])
            ->when(isset($where['type']),function ($query) use ($where){
                $query->where(['l.type'=>$where['type']]);
            })
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['l.shop_id'=>$where['shop_id']]);
            })
            ->field($field);
        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->field($field)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                if(!isset($v['coupon_name']) && isset($v['num'])) $v['num'] = null;
            }

        }

        return compact('count','list');
    }
}

